package logic

import (
	"30zk/rpc/internal/svc"
	"30zk/rpc/model/mysql"
	"30zk/rpc/order"
	"30zk/rpc/pkg"
	"context"
	"fmt"
	"github.com/google/uuid"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *order.OrderAddRequest) (*order.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	u := mysql.User{}
	err := u.GetUser(int(in.UserId))
	if err != nil {
		return nil, fmt.Errorf("用户查询失败")
	}
	if u.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if u.UserStatus == 2 {
		return nil, fmt.Errorf("用户冻结")
	}
	g := mysql.Good{}
	err = g.GetGood(int(in.GoodsId))
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if g.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}

	newString := uuid.NewString()
	o := mysql.Order{
		UserId:      int(in.UserId),
		GoodsId:     int(in.GoodsId),
		OrderSn:     newString,
		Amount:      g.GoodsPrice,
		Payment:     int(in.Payment),
		UserStatus:  1,
		OrderStatus: 1,
		GoodsTitle:  g.GoodsTitle,
		GoodsPrice:  g.GoodsPrice,
	}

	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	err = g.UpdateStock(g.GoodsStock)
	if err != nil {
		return nil, fmt.Errorf("更新失败")
	}
	float := strconv.FormatFloat(g.GoodsPrice, 'f', 2, 64)
	pay := pkg.NewALiPay()
	s := pay.Pay(g.GoodsTitle, newString, float)
	return &order.OrderAddResponse{
		OrderSn: newString,
		Key:     s,
	}, nil
}
